package com.example.dell.network.http;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import com.example.dell.basic.AppComplication;
import com.example.dell.been.BasicBeen;
import com.example.dell.utils.NetWorkUtils;
import com.example.dell.utils.PhoneTypeUtil;
import com.example.dell.utils.ToastUtils;
import com.example.dell.workactivity.mvp.LoginActivity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by luccc
 * Create Time: 2017/7/19
 * Description:
 */

public class OkhttpEnginen implements IHttpEngien {
    private              OkHttpClient client;
    private              Context      context;
    private              Call         call;
    private static final Handler      mHandler = new Handler(Looper.myLooper());

    public OkhttpEnginen(Context context) {
        client = new OkHttpClient();
        this.context = context;
    }

    @Override
    public void get(String url, Map<String, Object> params, final CallBack callBack) {
        //        long currentime = StringUtils.getCurrentime();
        //        int random = StringUtils.getRandom();
        Request request = new Request.Builder()
                //                .header("appkey",MyConfigConstant.appkey)
                //                .header("timestamp", currentime + "")
                //                .header("random",random+"")
                //                .header("sign", SignUtils.buildSign(currentime,random))
                .header("token", "")
                .url(url)
                .get()
                .build();
        call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(e.getMessage(), 0);
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String result = response.body().string();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onSuccess(result);
                    }
                });
            }
        });
    }

    @Override
    public void post(final String url, final CallBack callBack, RequestBody body) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("rom", PhoneTypeUtil.getTotalMemory());
            jsonObject.put("ram", PhoneTypeUtil.getAvailMemory(context));
            jsonObject.put("ver", PhoneTypeUtil.getSystemVersion());
            jsonObject.put("model", PhoneTypeUtil.getPhoneModel());
            jsonObject.put("imei", PhoneTypeUtil.getIMEI(context));
            jsonObject.put("brand", PhoneTypeUtil.getBrand());
            jsonObject.put("sdk", PhoneTypeUtil.getSDKVersion());
            jsonObject.put("av", PhoneTypeUtil.getVersionCode(context));
            jsonObject.put("scs", PhoneTypeUtil.getScs(context));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        final Request request = new Request.Builder()
                .header("PhoneUuid", PhoneTypeUtil.getPhoneSign(context))
                .header("token", "")
                .header("info", jsonObject.toString())
                .url(url)
                .post(body)
                .build();
        call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                        if (NetWorkUtils.isNetworkConnected(AppComplication.mContext)) {
                            callBack.onFailure("网络请求异常，请稍后重试", 0);
                        } else {
                            callBack.onFailure("你的网络不给力，请检查网络设置", 0);
                        }

                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body() != null ? response.body().string() : null;
                if (result != null) {
                    try {
                        Gson gson = new Gson();
                        final BasicBeen model = gson.fromJson(result, BasicBeen.class);


                        if (model == null) {

                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showToast("暂无返回结果");
                                    callBack.onFailure("暂无返回结果", 0);
                                }
                            });
                            return;
                        }

                        if (model.getResultCode() != null) {
                            if (model.getResultCode().equals("105")) {

                                if (url.equals("www.10086.com")) {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastUtils.showToast( "请先登录");
                                            callBack.onFailure("请先登录", 0);
                                        }
                                    });
                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            Intent intent = new Intent(context, LoginActivity.class);
                                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            context.startActivity(intent);
                                            callBack.onFailure("请先登录", 0);
                                        }
                                    });

                                }


                            } else if (model.getResultCode().equals("500")) {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        callBack.onFailure(model.getMessage(), 0);
                                    }
                                });

                            } else {
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        callBack.onSuccess(result);
                                    }
                                });

                            }
                        } else {
                            mHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtils.showToast( "暂无返回结果");
                                    callBack.onFailure("暂无返回结果", 0);
                                }
                            });
                        }
                    } catch (final JsonSyntaxException e) {

                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showToast("暂无返回结果，请稍后重试");
                                callBack.onFailure("暂无返回结果，请稍后重试", 0);
                            }
                        });

                    }
                } else {

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtils.showToast("暂无返回结果");
                            callBack.onFailure("暂无返回结果", 0);
                        }
                    });
                }
            }
        });
    }

    @Override
    public Call getCall() {
        if (call != null) {
            return call;
        } else {
            return null;
        }
    }
}
